package com.phpxiu.app.presenters;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.LBSInfo;
import com.phpxiu.app.model.LiveRoomHost;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.viewinterface.EnterQuiteRoomView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.tencent.TIMCallBack;
import com.tencent.TIMConversationType;
import com.tencent.TIMGroupManager;
import com.tencent.TIMManager;
import com.tencent.TIMValueCallBack;
import com.tencent.av.sdk.AVContext;
import com.tencent.av.sdk.AVRoomMulti;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.util.ArrayList;


/**
 * @file
 * @brief 进入房间业务流程逻辑处理类
 * @author 吴金洲
 * @note  进入房间业务流程逻辑处理类
 *
 */
@Deprecated
public class EnterQuitePresenter extends BasePresenter {
    private EnterQuiteRoomView mStepInOutView;
    private Context mContext;
    private static final String TAG = EnterQuitePresenter.class.getSimpleName();
    private static boolean isInChatRoom = false;
    private static boolean isInAVRoom = false;
    private ArrayList<String> video_ids = new ArrayList<String>();
    private String[] friendIds;//私密直播ids
    private String mLiveType="0";
    private static final int TYPE_MEMBER_CHANGE_IN = 1;//进入房间事件。
    private static final int TYPE_MEMBER_CHANGE_OUT = 2;//退出房间事件。
    private static final int TYPE_MEMBER_CHANGE_HAS_CAMERA_VIDEO = 3;//有发摄像头视频事件。
    private static final int TYPE_MEMBER_CHANGE_NO_CAMERA_VIDEO = 4;//无发摄像头视频事件。
    private static final int TYPE_MEMBER_CHANGE_HAS_AUDIO = 5;//有发语音事件。
    private static final int TYPE_MEMBER_CHANGE_NO_AUDIO = 6;//无发语音事件。
    private static final int TYPE_MEMBER_CHANGE_HAS_SCREEN_VIDEO = 7;//有发屏幕视频事件。
    private static final int TYPE_MEMBER_CHANGE_NO_SCREEN_VIDEO = 8;//无发屏幕视频事件。
    private String[] streamUrls;

    public EnterQuitePresenter(Context context, EnterQuiteRoomView view) {
        mContext = context;
        mStepInOutView = view;
    }

    /**
     * 设置直播参数 私密好友id及直播类型
     * @param friendIds
     */
    public void setLiveParams(String type,String[] friendIds) {
        mLiveType=type;
        this.friendIds = friendIds;
    }

    /**
     * 进入一个直播房间流程
     */
    public void startEnterRoom() {
        if (MySelfInfo.getInstance().getIdStatus() == Constants.HOST) {
            createLive();
        } else {
            joinLive(CurLiveInfo.getRoomNum());
        }

    }


    /**
     * 1.8.4SDK变动2017-01-12
     */
    private AVRoomMulti.EventListener mRoomDelegate= new AVRoomMulti.EventListener() {
        @Override
        public void onEnterRoomComplete(int result, String s) {
            KKYUtil.log(TAG, "AVRoomMulti-->加入视频房间" + result);
            if (result == 0) {
                QavsdkControl.getInstance().setAvRoomMulti(QavsdkControl.getInstance().getAVContext().getRoom());
                //只有进入房间后才能初始化AvView
                isInAVRoom = true;
                initAudioService();
                if(mStepInOutView==null){//结束进入房间返回
                    if(mContext!=null){
                        Toast.makeText(mContext, "成功进入房间但是不显示", Toast.LENGTH_LONG).show();
                    }
                    CrashReport.postCatchedException(new NullPointerException("EnterLiveHelper.java:93-mStepInOutView==null,成功进入房间，但是不显示操作界面"));
                }
                if(mStepInOutView!=null) {
                    mStepInOutView.enterRoomComplete(MySelfInfo.getInstance().getIdStatus(), true);
                }
            } else {
                if(mStepInOutView!=null) {
                    mStepInOutView.enterRoomComplete(MySelfInfo.getInstance().getIdStatus(), false);
                }
            }
        }

        @Override
        public void onExitRoomComplete() {
            KKYUtil.log(TAG, "AVRoomMulti-->离开视频房间");
            isInAVRoom = false;
            quiteIMChatRoom();//退出IM聊天室
            CurLiveInfo.setCurrentRequestCount(0);
            uninitAudioService();//释放音频服务资源
            //通知业务服务器直播结束
            //notifyServerLiveEnd();
            if (mStepInOutView != null) {
                mStepInOutView.quiteRoomComplete(MySelfInfo.getInstance().getIdStatus(), true);
            }
        }

        @Override
        public void onRoomDisconnect(int i, String s) {

        }

        @Override
        public void onSwitchRoomComplete(int i, String s) {

        }

        @Override
        public void onEndpointsUpdateInfo(int eventid, String[] updateList) {
            switch (eventid) {
                case TYPE_MEMBER_CHANGE_IN:
                    //房间成员大于50个时，不会执行这一步
                    if(mStepInOutView!=null) {
                        mStepInOutView.memberJoinLive(updateList);
                    }
                    break;
                case TYPE_MEMBER_CHANGE_OUT:
                    //房间成员大于50个时，不会执行这一步
                    if(mStepInOutView!=null) {
                        mStepInOutView.memberQuiteLive(updateList);
                    }
                    break;
                case TYPE_MEMBER_CHANGE_HAS_CAMERA_VIDEO://新增某个上行视频画面，减少不会调用
                    video_ids.clear();
                    String testIds="";
                    for (String id : updateList) {
                        video_ids.add(id);
                        testIds=testIds+id+",";
                    }
                    if(RoomVideoRoom.DEBUG_INTERACT&&mContext!=null) {
                        Toast.makeText(mContext, "视频变更：" + testIds, Toast.LENGTH_LONG).show();
                    }
                    Intent intent = new Intent(Constants.ACTION_CAMERA_OPEN_IN_LIVE);
                    intent.putStringArrayListExtra("ids", video_ids);
                    if(mContext!=null){
                        mContext.sendBroadcast(intent);
                    }
                    break;
                case TYPE_MEMBER_CHANGE_HAS_AUDIO:
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPrivilegeDiffNotify(int i) {

        }

        @Override
        public void onSemiAutoRecvCameraVideo(String[] strings) {
            if(mStepInOutView!=null) {
                mStepInOutView.alreadyInLive(strings);
            }
        }

        @Override
        public void onCameraSettingNotify(int i, int i2, int i3) {

        }

        @Override
        public void onRoomEvent(int i, int i2, Object o) {

        }

        @Override
        public void onDisableAudioIssue() {

        }

        @Override
        public void onHwStateChangeNotify(boolean b, boolean b2, boolean b3, String s) {

        }
    };


    /**
     * 1_1 创建一个直播
     */
    private void createLive() {
        createIMChatRoom();
    }

    /**
     * 1_2创建一个IM聊天室
     */
    private void createIMChatRoom() {
        final ArrayList<String> list = new ArrayList<String>();
        final String roomName = "AVChatRoom"+ MySelfInfo.getInstance().getMyRoomNum();
        TIMGroupManager.getInstance().createGroup("AVChatRoom", list, roomName, "" + MySelfInfo.getInstance().getMyRoomNum(), new TIMValueCallBack<String>() {
            @Override
            public void onError(int i, String s) {
                //已在房间中,重复进入房间-->创建视频房间
                if (i == 10025) {
                    isInChatRoom = true;
                    createAVRoom(MySelfInfo.getInstance().getMyRoomNum());
                    return;
                }
                // 创建IM房间失败，提示失败原因，并关闭等待对话框
                quiteLive();
            }

            @Override
            public void onSuccess(String s) {
                isInChatRoom = true;
                //创建AV房间
                createAVRoom(MySelfInfo.getInstance().getMyRoomNum());
            }
        });

    }



    /**
     * 1_3创建一个AV房间
     */
    private void createAVRoom(int roomNum) {
        EnterAVRoom(roomNum);
    }

    /**
     * 初始化Usr
     */
    public void initAvUILayer(View avView) {
        if(QavsdkControl.getInstance().getAVContext()==null){
            if(mContext!=null&&KKYUtil.DEBUG){
                Toast.makeText(mContext,TAG+"--AVContext实例为空",Toast.LENGTH_LONG).show();
            }
        }
        //初始化AVSurfaceView
        if (QavsdkControl.getInstance().getAVContext() != null&&mContext!=null) {
            QavsdkControl.getInstance().initAvUILayer(mContext.getApplicationContext(), avView);
        }

    }


    /**
     * 1_5上传房间信息
     */
    public void notifyServerCreateRoom() {
        OKHttpParam param= OKHttpParam.builder(false);
        if (TextUtils.isEmpty(CurLiveInfo.getTitle())) {
            //param.put("title", mContext.getString(R.string.text_live_default_title));//不设置默认标题
            param.put("title","");
        } else {
            param.put("title", CurLiveInfo.getTitle());
        }
        param.put("liveUrl",streamUrls);
        param.put("cover", MySelfInfo.getInstance().getAvatar());
        param.put("chatRoomId", CurLiveInfo.getChatRoomId());
        param.put("avRoomId", CurLiveInfo.getRoomNum());
        param.put("host", new LiveRoomHost(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getAvatar(), MySelfInfo.getInstance().getNickName()));
        if (mContext==null){
            return;
        }
        if(CurLiveInfo.getAddress()==null||"".equals(CurLiveInfo.getAddress())){
            param.put("lbs", new LBSInfo(CurLiveInfo.getLong1(), CurLiveInfo.getLat1(),mContext.getString(R.string.default_location)));
        }else{
            param.put("lbs", new LBSInfo(CurLiveInfo.getLong1(), CurLiveInfo.getLat1(), CurLiveInfo.getAddress()));
        }
        if(friendIds!=null&&friendIds.length>0){
            param.put("userlist",friendIds);
        }else {
            param.put("userlist","[]");
        }
        param.put("type",mLiveType);
        KKYUtil.log("直播上报参数：" + param.jsonParam());
        OKHttp.post(HttpConfig.POST_LIVE_INFO, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                String result = ((OKHttpResponseModel) model).getResponseStr();
                KKYUtil.log(TAG, "上报结果：" + result);
                mStepInOutView.startSuccess();
            }

            @Override
            public void onErr(String errMsg) {
                KKYUtil.log(TAG, "上报失败：" + errMsg);
            }
        });
    }


    /**
     * 2_1加入一个房间
     */
    private void joinLive(int roomNum) {
        joinIMChatRoom(roomNum);
    }

    /**
     * 2_2加入一个聊天室
     */
    private void joinIMChatRoom(int chatRoomId) {
        TIMGroupManager.getInstance().applyJoinGroup("" + chatRoomId, Constants.APPLY_CHATROOM + chatRoomId, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                //已经在是成员了
                if (i == Constants.IS_ALREADY_MEMBER) {
                    joinAVRoom(CurLiveInfo.getRoomNum());
                    isInChatRoom = true;
                } else {
                    //Toast.makeText(mContext,"进入房间直播已结束!",Toast.LENGTH_LONG).show();
                    //加入房间时直播已结束!
                    //quiteLive();
                    if(mStepInOutView==null){//结束进入房间返回
                        if(KKYUtil.DEBUG&&mContext!=null) {
                            Toast.makeText(mContext, "进入房间直播已结束!", Toast.LENGTH_LONG).show();
                        }
                        CrashReport.postCatchedException(new NullPointerException("EnterLiveHelper.java:280-mStepInOutView==null"));
                    }
                    if(mStepInOutView!=null) {
                        mStepInOutView.onEndEnter();//edit by wujinzhou
                    }
                }
                CrashReport.postCatchedException(new NullPointerException("EnterLiveHelper.java:280-mStepInOutView==null"));
            }
            @Override
            public void onSuccess() {
                isInChatRoom = true;
                joinAVRoom(CurLiveInfo.getRoomNum());
            }
        });

    }

    /**
     * 2_2加入一个AV房间
     */
    private void joinAVRoom(int avRoomNum) {
        EnterAVRoom(avRoomNum);
    }


    /**
     * 退出房间
     */
    public void quiteLive() {
        quiteAVRoom();
    }


    public void onDestory() {
        mStepInOutView = null;
        mContext = null;
        friendIds=null;
    }




    /**
     * 退出一个AV房间
     */
    private void quiteAVRoom() {
        //已创建或进入视频房间，则退出视频房间
        if (isInAVRoom == true) {
            QavsdkControl.getInstance().getAVContext().exitRoom();//异步退出音视频房间，退出成功一定会调用AVRoomMulti.Delegate的onExitRoomComplete(int result)
            isInAVRoom=false;
        } else {
            quiteIMChatRoom();//退出聊天室
            CurLiveInfo.setCurrentRequestCount(0);
            uninitAudioService();
            if(mStepInOutView!=null) {
                mStepInOutView.quiteRoomComplete(MySelfInfo.getInstance().getIdStatus(), true);
            }
        }
    }

    /**
     * 退出IM房间
     */
    private void quiteIMChatRoom() {
        if ((isInChatRoom == true)) {
            //主播解散群
            if (MySelfInfo.getInstance().getIdStatus() == Constants.HOST) {
                TIMGroupManager.getInstance().deleteGroup("" + CurLiveInfo.getRoomNum(), new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                    }

                    @Override
                    public void onSuccess() {
                        isInChatRoom = false;
                    }
                });
                TIMManager.getInstance().deleteConversation(TIMConversationType.Group, "" + MySelfInfo.getInstance().getMyRoomNum());
            } else {
                //成员退出群
                TIMGroupManager.getInstance().quitGroup("" + CurLiveInfo.getRoomNum(), new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                    }

                    @Override
                    public void onSuccess() {
                        isInChatRoom = false;
                    }
                });
            }

            //
        }
    }


    /**
     * 进入AV房间
     *
     * @param roomNum
     */
    private void EnterAVRoom(int roomNum) {
        AVContext avContext = QavsdkControl.getInstance().getAVContext();
        byte[] authBuffer = null;//权限位加密串；TODO：请业务侧填上自己的加密串

        AVRoomMulti.EnterParam.Builder enterRoomParam = new AVRoomMulti.EnterParam.Builder(roomNum);
        if (MySelfInfo.getInstance().getIdStatus() == Constants.HOST) {
            enterRoomParam.auth(Constants.HOST_AUTH, authBuffer).avControlRole(Constants.HOST_ROLE).autoCreateRoom(true).isEnableMic(true).isEnableSpeaker(true);//；TODO：主播权限 所有权限
        } else {
            enterRoomParam.auth(Constants.NORMAL_MEMBER_AUTH, authBuffer).avControlRole(Constants.NORMAL_MEMBER_ROLE).autoCreateRoom(false).isEnableSpeaker(true);
        }
        enterRoomParam.audioCategory(Constants.AUDIO_VOICE_CHAT_MODE).videoRecvMode(AVRoomMulti.VIDEO_RECV_MODE_SEMI_AUTO_RECV_CAMERA_VIDEO);
        if (avContext != null) {
            // create room
            avContext.enterRoom(mRoomDelegate, enterRoomParam.build());
        }
    }


    private void initAudioService() {
        if ((QavsdkControl.getInstance() != null) && (QavsdkControl.getInstance().getAVContext() != null) && (QavsdkControl.getInstance().getAVContext().getAudioCtrl() != null)) {
            QavsdkControl.getInstance().getAVContext().getAudioCtrl().startTRAEService();
        }
    }

    private void uninitAudioService() {
        if ((QavsdkControl.getInstance() != null) && (QavsdkControl.getInstance().getAVContext() != null) && (QavsdkControl.getInstance().getAVContext().getAudioCtrl() != null)) {
            QavsdkControl.getInstance().getAVContext().getAudioCtrl().stopTRAEService();
        }
    }

    public String[] getStreamUrls() {
        return streamUrls;
    }

    public void setStreamUrls(String[] streamUrls) {
        this.streamUrls = streamUrls;
    }
}
